package sword_offer;

import common.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName _32_1_LevelOrderTree
 * @Description: 从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
 * @Author: yongliang.ma
 * @Create_time:2022/10/10 13:25
 */
public class _32_2_LevelOrderTree {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null)
            return new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        int size = 0;
        while (!deque.isEmpty()){
            // 用size进行分层
            size = deque.size();
            List<Integer> temp = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = deque.poll();
                temp.add(treeNode.val);
                if (treeNode.left != null)
                    deque.offer(treeNode.left);
                if (treeNode.right != null)
                    deque.offer(treeNode.right);
            }
            result.add(temp);
        }

        return result;
    }
}
